<template>

  <div>
    <el-divider></el-divider>
    <!--操作按钮-->
    <div>
      <div style="display: flex;justify-content: space-between">
        <div>
          <el-input v-model="text" style="width: 300px;margin-right: 10px;"
                    size="small" placeholder="请输入课程名称" clearable @clear="initTable">
          </el-input>
          <el-button type="primary" @click="textPage(text)" icon="el-icon-search"
                     size="small" style="width: 90px;">搜索
          </el-button>
        </div>
        <div>
          <el-button v-if="user.teacher" type="primary" plain @click="thenAdd()" icon="el-icon-circle-plus"
                     size="small">添加
          </el-button>
          <el-button v-if="user.teacher" type="danger" plain icon="el-icon-s-unfold" @click="getTemplate()"
                     size="small">报名模板
          </el-button>
          <el-button v-if="user.teacher" type="warning" plain icon="el-icon-milk-tea" @click="importFileCPM=true"
                     size="small">批量报名
          </el-button>
          <el-button v-if="user.teacher"  type="success" plain icon="el-icon-reading" @click="initErrPageTable()"
                     size="small">错误记录
          </el-button>
          <el-button v-if="user.teacher" type="danger" @click="idsDelete(ids)" icon="el-icon-delete"
                     :disabled="ids.length===0" size="small">批量删除
          </el-button>
        </div>
      </div>
    </div>
    <!--分页列表-->
    <div class="tableSet">
      <!--handleSelectionChange 复选框点击事件，就是每一条数据前面的勾选按钮-->
      <el-table
          border
          ref="multipleTable"
          :data="page.data"
          tooltip-effect="dark"
          style="width: 100%"
          size="small"
          @selection-change="handleSelectionChange"
          v-loading="loading">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="itm_id"
            label="编号"
            width="50">
        </el-table-column>
        <el-table-column
            prop="itm_uuid"
            label="课程编码"
            width="110"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="itm_title"
            label="课程名称"
            width="100"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="itm_remarks"
            label="课程描述"
            width="250"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="itmUserName"
            label="创建人"
            width="100"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="itm_create_time"
            label="创建时间"
            width="100"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            v-if="user.teacher"
            prop="itm_status"
            label="状态"
            width="100"
            show-overflow-tooltip>
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.itm_status"
                active-color="#13ce66"
                inactive-color="#ff4949" @change="updateStatus(scope.row)">
            </el-switch>
            {{ scope.row.itm_status === true ? '发布' : '未发布' }}
          </template>
        </el-table-column>
        <el-table-column
            label="操作">
          <template slot-scope="scope">
            <!--$index 下标，row 行数据-->
            <el-button
                v-if="user.teacher && scope.row.itm_reserve_1 === '1'"
                size="mini"
                @click="thenUpdate(scope.$index, scope.row)">编辑
            </el-button>
            <!-- type="danger" 删除按钮红色-->
            <el-button
                v-if="user.teacher && scope.row.itm_reserve_1 === '1'"
                size="mini"
                type="danger"
                @click="thenDelete(scope.$index, scope.row)">删除
            </el-button>
            <el-button
                v-if="user.teacher && scope.row.itm_reserve_1 === '1'"
                size="mini"
                type="warning"
                @click="thenSignUp(scope.$index, scope.row)">手动报名
            </el-button>
            <el-button
                size="mini"
                type="primary"
                @click="thenDetails(scope.$index, scope.row)">作业详情
            </el-button>
            <el-button
                v-if="user.teacher && scope.row.itm_reserve_1 === '1'"
                size="mini"
                type="danger" plain
                @click="thenEndCourse(scope.$index, scope.row)">结束课程
            </el-button>
            <el-button
                v-if="user.teacher && scope.row.itm_reserve_1 === '0'"
                size="mini"
                type="success"
                @click="thenCourseResult(scope.$index, scope.row)">查看成绩
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--手动报名-->
    <div>
      <el-dialog
          title="课程报名"
          :visible.sync="dialogThenSignUp"
          width="30%"
          :before-close="handleClose"
          center>
        <el-form :label-position="textAlign"
                 :model="signUp" status-icon ref="signUpRuleForm" label-width="100px" class="demo-ruleForm"
                 :rules="signUpRules">
          <el-form-item label="学生学号:" prop="username">
            <el-input style="width: 92%" v-model="signUp.username" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <!--@keydown.enter.native 键盘回车触发-->
            <el-button type="primary" @click="signUpSubmitForm(signUp)">提交</el-button>
            <el-button @click="cancel()">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>


    <!--分页控制组件-->
    <div class="block">
      <!-- 当前条数，@size-change 自动带过来的-->
      <!-- 当前页，@current-change 自动带过来的-->
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="size"
          layout="total, prev, pager, next, sizes, jumper"
          :total="page.total">
      </el-pagination>

    </div>

    <!--导入记录-->
    <el-dialog
        title="导入记录:"
        width="50%"
        :before-close="handleCloseErrPage"
        :visible.sync="dialogErrPage">
      <!--分页列表-->
      <div class="tableSet">
        <!--handleSelectionChange 复选框点击事件，就是每一条数据前面的勾选按钮-->
        <el-table
            border
            ref="multipleTable"
            :data="errPage.data"
            tooltip-effect="dark"
            style="width: 100%"
            size="small"
            v-loading="loading">
          <el-table-column prop="erId" label="数据编号" width="150px"></el-table-column>
          <el-table-column prop="erText" label="错误信息" width="400px"></el-table-column>
          <el-table-column prop="erCreateTime" label="导入时间" width="262px"></el-table-column>
        </el-table>
      </div>
      <!--错误记录分页-->
      <div class="block">
        <!--/**
        * 当前条数，@size-change 自动带过来的
        * @param val
        */-->
        <!-- /**
       * 当前页，@current-change 自动带过来的
       */-->
        <el-pagination
            background
            @size-change="handleSizeChangeErrPage"
            @current-change="handleCurrentChangeErrPage"
            :current-page="errCurrentPage"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="errSize"
            layout="total, prev, pager, next, sizes, jumper"
            :total="errPage.total">
        </el-pagination>
        <el-button style="margin-top: 10px;" @click="dialogErrPage = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!--添加课程-->
    <div>
      <el-dialog
          :title="addData.itm_id === 0? '添加':'编辑'"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose"
          center>
        <el-form :label-position="textAlign"
                 :model="addData" status-icon ref="ruleForm" label-width="100px" class="demo-ruleForm"
                 :rules="fromRules">
          <el-form-item label="课程名称:" prop="itm_title">
            <el-input style="width: 92%" v-model="addData.itm_title" clearable></el-input>
          </el-form-item>
          <el-form-item label="课程描述:" prop="itm_remarks">
            <el-input style="width: 92%" v-model="addData.itm_remarks" clearable></el-input>
          </el-form-item>
          <el-form-item label="状态:">
            <el-radio v-model="addData.itm_status" :label="true" border>发布</el-radio>
            <el-radio v-model="addData.itm_status" :label="false" border>未发布</el-radio>
          </el-form-item>
          <el-form-item>
            <!--@keydown.enter.native 键盘回车触发-->
            <el-button type="primary" @click="submitForm()">提交</el-button>
            <el-button @click="cancel()">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!--导入-->
    <el-dialog title="上传文件" :visible.sync="importFileCPM" width="400px" @close="cancel()">
      <!--批量导入弹窗-->
      <el-upload
          ref="upload"
          action="../course/user-enroll"
          class="upload-demo"
          :multiple="false"
          :limit="1"
          accept=".xlsx"
          :auto-upload="false"
          :headers="headers"
          :data="param"
          :on-change="handleChange"
          :on-success="success"><!--:headers="headers"-->
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
      </el-upload>
      <div slot="footer">
        <el-button type="primary" @click="cancels">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>

    <!--模板-->
    <el-dialog
        title="模板文件"
        :visible.sync="templateCPM"
        width="30%"
        :before-close="handleClose">
      <div style="height: 150px">
        <el-form label-position="left"
                 :model="tempData" status-icon ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="模板路径:" prop="name">
            <el-input style="width: 92%" v-model="tempData.title" disabled></el-input>
          </el-form-item>
          <span>备注：若D盘没有该文件夹，系统会自动创建。</span>
          <br>
          <br>
          <span>默认路径为 【D:\student-info\】</span>
        </el-form>
      </div>
      <div style="text-align: center">
        <!--@keydown.enter.native 键盘回车触发-->
        <el-button type="primary" @click="templateSubmitForm(tempData)">提交</el-button>
        <el-button @click="templateCPM = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import uploadFile from "@/components/file/upload-file";

export default {
  name: "PerEc",
  //导入组件
  components: {
    uploadFile
  },
  data() {
    return {
      // 手动报名弹窗
      dialogThenSignUp: false,
      // 获取当前登录用户信息，在manin.js登录验证存进的session，接口获取的是一个json格式字符串，转换为js对象
      user: JSON.parse(window.sessionStorage.getItem('user')),
      tempData: {
        title: 'D:\\student-info\\'
      },
      // 模板弹窗
      templateCPM: false,
      // 错误记录弹窗
      dialogErrPage: false,
      // 导入文件弹窗
      importFileCPM: false,
      // 文件
      file: '',
      // 文件格式
      param: {
        ContentType: 'multipart/form-data'
      },
      // 文件请求头
      headers: {
        'authorization': window.sessionStorage.getItem(('tokenStr'))
      },
      defaultTeacher: true,
      defaultStudent: false,
      // 表单文字对其方式
      textAlign: 'right',
      // 加载动画
      loading: false,
      // 弹窗控制，true打开弹窗，false关闭弹窗
      dialogVisible: false,
      // 手动报名对象
      signUp: {
        itmId: '',
        username: ''
      },
      // 增加修改对象
      addData: {
        itm_id: 0,
        itm_uuid: '',
        itm_title: '',
        itm_remarks: '',
        itm_status: ''
      },
      // 批量删除数组
      deleteIds: [],
      // 分页对象
      page: {
        total: 0,
        data: [{}]
      },
      errPage: {
        total: 0,
        data: [{}]
      },
      // 第几页，默认第一页
      currentPage: 1,
      // 每页大小，默认10条数据一页
      size: 10,
      // 第几页，默认第一页
      errCurrentPage: 1,
      // 每页大小，默认10条数据一页
      errSize: 10,
      // 分页搜索文本
      text: '',
      // 表单正则校验
      fromRules: {
        itm_title: [
          {required: true, message: '请输入课程名称', trigger: 'blur'}
        ],
        itm_remarks: [
          {required: true, message: '请输入课程描述', trigger: 'blur'}
        ]
      },
      signUpRules: {
        username: [
          {required: true, message: '请输入学生学号', trigger: 'blur'}
        ]
      },
      // 批量操作ids
      ids: []
    }
  },
  // 一进入页面就要调用的接口放到 mounted 里面，比如页面表格分页
  mounted() {
    this.initTable();
  },
  methods: {
    /**
     * 文本搜索
     */
    textPage(text) {
      this.text = text;
      this.initTable();
    },
    /**
     * 分页数据
     */
    initTable() {
      this.loading = true
      this.getRequestParams("/course/page", {
        currentPage: this.currentPage,
        size: this.size,
        text: this.text,
        userId: this.user.teacher ? null : this.user.id
      }).then(data => {
        if (data) {
          this.page = data
          this.loading = false;
        }
      })
    },
    initErrPageTable() {
      this.loading = true
      // 打开错误记录表格弹窗
      this.dialogErrPage = true
      this.getRequestParams("/errorRecord/page", {
        currentPage: this.errCurrentPage, size: this.errSize,
        type: 'course'
      }).then(data => {
        if (data) {
          this.errPage = data
          this.loading = false;
        }
      })
    },
    /**
     * 提交表单
     */
    submitForm() {
      console.log(this.addData)
      // 正则校验表单数据
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {// 验证通过
          if (this.addData.itm_id === 0) {
            // 调用添加接口
            this.postRequestData('/course/add', this.addData).then(data => {
              // 添加成功
              if (data) {
                // 刷新表格数据
                this.initTable();
              }
            })
            // 关闭弹窗
            this.dialogVisible = false;
            this.addData = {itm_status: true};
          } else {
            // 调用添加接口
            this.postRequestData('/course/update', this.addData).then(data => {
              // 修改成功
              if (data) {
                // 刷新表格数据
                this.initTable();
              }
            })
            // 关闭弹窗
            this.dialogVisible = false;
            // 默认选择按钮
            this.addData = {itm_status: true};
          }
        } else {
          this.$message.error('请输入必填项!');
          return false;
        }
      });
    },
    /**
     * 复选框
     */
    handleSelectionChange(val) {
      this.ids = val
    },
    /**
     * 添加按钮点击事件
     */
    thenAdd() {
      this.addData = {itm_id: 0, itm_status: true};
      this.dialogVisible = true;
      // this.$refs.ruleForm.resetFields();
    },
    /**
     * 编辑按钮点击事件
     */
    thenUpdate(index, data) {
      this.addData = {
        itm_id: data.itm_id,
        itm_uuid: data.itm_uuid,
        itm_title: data.itm_title,
        itm_remarks: data.itm_remarks,
        itm_status: data.itm_status
      };
      this.dialogVisible = true;
    },
    /**
     * 删除点击事件
     */
    thenDelete(index, data) {
      this.$confirm('确定删除此记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        this.postRequestParams('/course/delete', {id: data.itm_id}).then(res => {
          if (res) {
            // 刷新表格
            this.initTable();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '已取消'
        });
      });

    },
    /**
     * 跳转-作业详情
     */
    thenDetails(index, data) {
      this.$router.push({
        path: '/sal/sob',
        query: {
          itmId: data.itm_id,
          itmStatus: data.itm_reserve_1
        }
      })
    },
    /**
     * 查看课程成绩
     */
    thenCourseResult(index, data) {
      this.$router.push({
        path: '/emp/empAdv',
        query: {
          itmId: data.itm_id
        }
      })

    },
    /**
     * 批量删除
     */
    idsDelete(ids)
{
  console.log(ids)
  this.$confirm('此操作将永久删除[' + this.ids.length + ']记录！, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let x = [];
    for (let item of ids) {
      x.push(item.itm_id);
    }
    // 调用删除接口
    this.postRequestData('/course/delete-ids', x).then(res => {
      if (res) {
        // 刷新表格
        this.initTable();
      }
    })
  }).catch(() => {
    this.$message({
      type: 'success',
      message: '已取消'
    });
  });
}
,
/**
 * 取消
 */
cancel()
{
  // 关闭弹窗
  this.dialogThenSignUp = false
  // 初始化
  this.signUp = {}
  // 关闭弹窗
  this.dialogVisible = false;
  // 初始化
  this.addData = {itm_status: true};
}
,
/**
 * 关闭弹窗
 * @param done
 */
handleClose(done)
{
  this.$confirm('确认关闭？')
      .then(_ => {// 确定关闭
        // 初始化
        this.addData = {itm_status: true};
        // 清除表单校验
        this.$refs.ruleForm.resetFields();
        done();
      })
      .catch(_ => {// 不关闭弹窗

      });
}
,
handleCloseErrPage()
{
  this.$confirm('确认关闭？')
      .then(_ => {// 确定关闭
        this.dialogErrPage = false
        done();
      })
      .catch(_ => {// 不关闭弹窗

      });
}
,
/**
 * val 这个是当前页，@current-change 自动带过来的
 */
handleCurrentChange(val)
{
  this.currentPage = val;
  this.initTable();
}
,
/**
 * val 这个是当前条数，@size-change 自动带过来的
 * @param val
 */
handleSizeChange(val)
{
  this.size = val;
  this.initTable();
}
,
handleCurrentChangeErrPage(val)
{
  this.errCurrentPage = val;
  this.initErrPageTable();
}
,
/**
 * val 这个是当前条数，@size-change 自动带过来的
 * @param val
 */
handleSizeChangeErrPage(val)
{
  this.size = val;
  this.initErrPageTable();
}
,
handleChange(file, fileList)
{
  if (file) {
    if (file.name.indexOf('xlsx') !== -1) {
      this.file = file
    } else {
      this.$message({
        message: '请上传xlsx格式的文件！',
        type: 'warning'
      });
    }
  }
}
,
openUploadFile(val)
{
  this.param.type = val
  this.importFileCPM = true
}
,
cancels()
{
  // 参数类型
  this.param.type = ''
  // 关闭弹窗
  this.importFileCPM = false
  // 清理文件
  this.$refs.upload.clearFiles()
}
,
submit()
{
  if (this.file) {
    // 提交文件
    this.$refs.upload.submit();
    // 关闭弹窗
    this.importFileCPM = false
    // 刷新列表
    this.initTable()
  } else {
    this.$message({
      message: '请上传xlsx格式的文件！',
      type: 'warning'
    });
  }
}
,
success(response, file, fileList)
{
  this.initTable()
}
,
/**
 * 获取模板文件
 */
getTemplate()
{
  this.templateCPM = true
  // this.postRequestData("/getTemplate").then(data => {
  //   if (data) {
  //     console.log(data)
  //     let a = document.createElement('a')
  //     a.download = ''
  //     a.href = data.obj
  //     a.click()
  //   }
  // })
}
,
/**
 * 修改状态
 */
updateStatus(data)
{
  console.log(data)
  this.postRequestData("/course/update", {itm_id: data.itm_id, itm_status: data.itm_status}).then(data => {
    if (data) {
      this.initTable()
    }
  })
}
,
/**
 * 模板文件
 * @param data
 */
templateSubmitForm(data)
{
  this.postRequestParams("/course/getTemplate", {path: data.title})
  this.templateCPM = false
  this.initTable()
}
,
// 手动报名
thenSignUp(index, data)
{
  this.dialogThenSignUp = true
  this.signUp = {itmId: data.itm_id}
}
,
// 手动报名提交
signUpSubmitForm(data)
{
  this.$refs.signUpRuleForm.validate((valid) => {
    if (valid) {
      this.postRequestParams('/course/manual-enroll', data)
      this.initTable()
      this.dialogThenSignUp = false
      this.signUp = {}
    } else {
      this.$message.error('请输入必填项!');
      return false;
    }
  });
}
,
// 结束课程
thenEndCourse(index, data)
{
  this.$confirm('课程结束后将生成该课程的所有学生成绩，无法在布置作业和打分，你确定结束课程吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 修改完成状态
    this.postRequestData('/course/update', {itm_id: data.itm_id, itm_reserve_1: '0'}).then(res => {
      if (res) {
        // 刷新表格
        this.initTable();
      }
    })
  }).catch(() => {
    this.$message({
      type: 'error',
      message: '已取消'
    });
  });
}


}


}
</script>

<style scoped>

.tableSet {
  margin-top: 10px;
}

.block {
  margin-top: 10px;
  text-align: center;
}


</style>